package com.sprite.framework.context;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import com.sprite.utils.UtilURL;

/**
 * 上下文环境
 * @author Jack
 */
public final class ContextEnvironment {

	private static Map<String, String> properties = new HashMap<>();
	
	public static String getProperty(String name) {
		return getProperty(name, null);
	}
	
	public static String getProperty(String name, String defaultValue) {
		String value =  properties.get(name);
		
		if(value == null) {
			value = System.getProperty(name);
		}
		
		return value == null ? defaultValue : value;
	}
	
	public static int getPropertyAsInt(String name) {
		String value = getProperty(name);
		
		return Integer.valueOf(value);
	}
	
	public static int getPropertyAsInt(String name, int defaultValue) {
		String value = getProperty(name);
		
		if(value == null) {
			return defaultValue;
		}
		return Integer.valueOf(value);
	}

	public static long getPropertyAsLong(String name) {
		String value = getProperty(name);

		return Long.valueOf(value);
	}

	public static long getPropertyAsLong(String name, long defaultValue) {
		String value = getProperty(name);

		if(value == null) {
			return defaultValue;
		}
		return Long.valueOf(value);
	}


	/**
	 * 加载properties 文件
	 * @param propertiesFile
	 * @param putToSystem	是否添加都系统变量中
	 * @throws IOException 配置文件读取错误
	 */
	public static void loadProperties(String propertiesFile, boolean putToSystem) throws IOException {
		if(!propertiesFile.endsWith(".properties")) {
			propertiesFile = propertiesFile.concat(".properties");
		}
		
		
		List<URL> list = UtilURL.fromResources(propertiesFile);
		for(URL url : list) {
			Properties properties = new Properties();
			properties.load(url.openStream());
			
			for(Object key : properties.keySet()) {
				ContextEnvironment.properties.put(key.toString(), properties.getProperty(key.toString()));
				if(putToSystem){
					System.setProperty(key.toString(), properties.getProperty(key.toString()));
				}
			}
			
		}
	}

	/**
	 * 加载properties文件
	 * @param propertiesFile 配置文件路径
	 * @throws IOException 配置文件转载错误
	 */
	public static void loadProperties(String propertiesFile) throws IOException {
		loadProperties(propertiesFile ,false );
	}

	public static void put(String key, String value) {
		ContextEnvironment.properties.put(key, value);
	}
}
